#include "cstdio"
#include "cstring"
#include "iostream"
#include "map"

using namespace std;

int _read(int &c) {
  static int ans = 0;
  static bool p;
  for (c = getchar(); c != EOF && c != '-' && (c < '0' || c > '9');
       c = getchar())
    ;
  if (c == EOF) return 0;
  if (c == '-')
    p = false, c = getchar();
  else
    p = true;
  for (ans = 0; c <= '9' && c >= '0'; c = getchar()) ans = ans * 10 + c - '0';
  return p ? ans : -ans;
}

int _read() {
  static int ans = 0, c;
  static bool p;
  for (c = getchar(); c != EOF && c != '-' && (c < '0' || c > '9');
       c = getchar())
    ;
  if (c == EOF) return 0;
  if (c == '-')
    p = false, c = getchar();
  else
    p = true;
  for (ans = 0; c <= '9' && c >= '0'; c = getchar()) ans = ans * 10 + c - '0';
  return p ? ans : -ans;
}

void _write(int ans) {
  static int a[20], n;
  if (ans == 0) {
    putchar('0');
    return;
  }
  if (ans < 0) {
    putchar('-');
    ans = -ans;
  }
  for (n = 0; ans; ans /= 10) a[n++] = ans % 10;
  for (n--; n >= 0; n--) putchar(a[n] + '0');
  return;
}

int main() {
  //    freopen("input.txt", "r", stdin);
  int c, n, a[100001], f[100001], sum;
  map<int, int> s;
  map<int, int>::iterator t;
  while (1) {
    s.clear();
    memset(f, 0x7f7f7f7f, sizeof f);
    n = _read(c);
    if (c == EOF) return 0;
    for (int i = 0; i < n; i++) a[i] = _read(c);
    for (int i = 0; i < n; i++) {
      s[a[i]]++;
    }
    for (int i = 0; i < n - 1; i++) {
      //            cout << "------------------------" << endl;
      //            cout << "Test" << i << endl;
      //            cout << "s[a[i]].second=" << s[a[i]] << endl;
      if (s[a[i]] == 1)
        s.erase(a[i]);
      else {
        s[a[i]]--;
        f[i] = 0;
        continue;
      }
      t = s.lower_bound(a[i]);
      //            cout << ">a[i]:" << t->first << endl;
      if (t != s.end())
        f[i] = abs(a[i] - t->first);
      else
        f[i] = 0x7f7f7f7f;
      if (t != s.begin()) {
        t--;
        //                cout << "<a[i]:" << t->first << endl;
        f[i] = min(f[i], abs(a[i] - t->first));
      }
      //            cout << "f[i]=" << f[i] << endl;
    }
    sum = 0;
    f[n - 1] = a[n - 1];
    for (int i = 0; i < n; i++) sum += f[i];
    _write(sum);
    putchar('\n');
  }
  return 0;
}
